import { user } from "@/api";
import { useUserStore } from "@/store";
import { App } from "vue";
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import Login from "../views/login/index.vue";

const routes: Readonly<RouteRecordRaw[]> = [
  {
    path: "/login",
    name: "login",
    component: Login,
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  let token = localStorage.getItem("token");
  //   如果没有token，只能访问登录页面
  if (!token && to.path !== "/login") {
    next("/login");
  }
  //   如果已经是登录页面，手动访问登录页面，强制跳回  原本的页面
  else if (token && to.path.toLocaleLowerCase() === "/login") {
    // 强制跳转回，原本的位置
    next(from.path);
  } else if (
    token &&
    userStore.menus.length === 0 &&
    router.getRoutes().length === 1 &&
    (from.path === "/" || from.path === "/login")
  ) {
    // 发送用户数据请求
    user.userInfoApi().then((res) => {
      if (res.code === 200) {
        // 将请求到的数据存到pinia中
        userStore.menus = res.data.menus;
        userStore.username = res.data.username;

        // 为了不和store里面的数据冲突，把数据进行一份拷贝
        const menus: IMenus[] = JSON.parse(JSON.stringify(res.data.menus));
        // 现在直接使用 userStore.menu 进行生成动态路由
        const parents: IActiveMenus[] = menus.filter(
          (menu) => menu.parentId === 0
        );
        menus.forEach((menu) => {
          // p 就是就一级路由
          const p = parents.find((p) => p.id === menu.parentId);
          if (p) {
            if (!p.children) {
              p.children = [];
            }
            p.children.push(menu);
          }
        });

        parents.forEach((parent) => {
          const route: RouteRecordRaw = {
            path: "/" + parent.name,
            name: parent.name,
            component: () => import("../views/Home/index.vue"),
            children: [],
            meta: {
              title: parent.title,
            },

          };
          parent.children?.forEach((child) => {
            route.children.push({
              path: `/${parent.name}/${child.name}`,
              name: child.name,
              component: () =>
                import(`../views/${parent.name}/${child.name}.vue`),

              meta: {
                title: child.title,
              },

            });
          });
          // 添加动态路由  添加是异步的
          router.addRoute(route);
        });
        //
        router.addRoute({
          path: "/",
          name: "home",
          redirect: "/index",
          component: () => import("../views/Home/index.vue"),
          children: [
            {
              path: "/index",
              name: "index",
              component: () => import("../views/index/index.vue"),

            },
          ],
        });
        next(to.fullPath);
      }
    });
  } else {

    next();
  }
});

export default (app: App<Element>) => {
  app.use(router);
};
export { router };
